package dongze.com.ckdj.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.Toast;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import dongze.com.ckdj.R;
import dongze.com.ckdj.adapter.StringArrayAdapter;
import dongze.com.ckdj.dagger.component.VehicleComponent;
import dongze.com.ckdj.data.entity.response.VehicleInformationDetail;
import dongze.com.ckdj.databinding.InformationItemTextTablerowBinding;
import dongze.com.ckdj.databinding.model.InformationItemTextModel;
import dongze.com.ckdj.map.MapUtil;
import io.reactivex.observers.DisposableObserver;

/**
 * Created by fanqwz on 2017/9/6.
 */

public class CheckInOperationItemSelectionActivity extends ProgressableActivity implements TextWatcher {
    MapUtil mapUtil;

    String key;
    String value;
    @Inject
    VehicleInformationDetail vehicleInformationDetail;

    //    @BindView(R.id.vin)
//    TextView vinTv;
//    @BindView(R.id.key)
//    TextView keyTv;
    @BindView(R.id.selectableList)
    ListView selectableList;
    @BindView(R.id.fuzzy_query_edit)
    EditText fuzzyEdit;
    @BindView(R.id.fuzzy_query_list)
    ListView fuzzyList;
    @BindView(R.id.empty_view)
    View empty;
    @BindView(R.id.progress)
    ProgressBar progressBar;
    @BindView(R.id.basic_info_container)
    TableLayout mBasicInfoLayout;
    @BindView(R.id.selection_container)
    View selectionContainer;
    @BindView(R.id.selectableList_empty_view)
    View selectableListEmptyView;
    DisposableObserver disposable;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapUtil = new MapUtil(getAppCompenent());
        handler = new Handler(getMainLooper());

        key = getIntent().getStringExtra("key");
        value = getIntent().getStringExtra("value");

        if (getComponent(VehicleComponent.class) != null) {
            getComponent(VehicleComponent.class).inject(this);
        } else {
            finish();
            return;
        }

        if (vehicleInformationDetail == null || TextUtils.isEmpty(key)) {
            new AlertDialog.Builder(this)
                    .setMessage("传入数据缺失")
                    .setCancelable(false)
                    .setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .create()
                    .show();
        }

        setContentView(R.layout.activity_check_in_operation_item_selection);
        ButterKnife.bind(this);

        fuzzyEdit.addTextChangedListener(this);
        fuzzyList.setEmptyView(empty);
        selectableList.setEmptyView(selectableListEmptyView);
        progressBar.setVisibility(View.INVISIBLE);

        InformationItemTextModel vin = new InformationItemTextModel();
        vin.setKey("车架号");
        vin.setValue(vehicleInformationDetail.getVin());
        addBasicInfoItem(vin);

        InformationItemTextModel item = new InformationItemTextModel();
        item.setKey("点检项");
        item.setValue(key);
        addBasicInfoItem(item);

        if (!TextUtils.isEmpty(value)) {
            selectionContainer.setVisibility(View.VISIBLE);
            query();
        } else {
            selectionContainer.setVisibility(View.GONE);
        }

        fuzzyQuery("");
    }

    @Override
    protected void onDestroy() {
        mapUtil.dispose();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        directReturn(null);
    }

    private void addBasicInfoItem(InformationItemTextModel model) {
        InformationItemTextTablerowBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_text_tablerow, mBasicInfoLayout, false);
        binding.getRoot().setTag(binding);
        binding.setVehicleInformationItemText(model);
        mBasicInfoLayout.addView(binding.getRoot());
    }

    private void query() {
        mapUtil.getCheckInOperationSelection(key, value, "1", vehicleInformationDetail.getBrand_code(), new DisposableObserver<List<String>>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(final List<String> value) {
                String[] arr = new String[value.size()];
                value.toArray(arr);
                selectableList.setAdapter(new StringArrayAdapter(
                        CheckInOperationItemSelectionActivity.this,
                        android.R.layout.simple_list_item_1,
                        android.R.id.text1,
                        arr));
                selectableList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent();
                        intent.putExtra("key", key);
                        intent.putExtra("value", value.get(position));
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
            }

            @Override
            public void onError(Throwable e) {
                finishProcessing();
            }

            @Override
            public void onComplete() {
                finishProcessing();
            }
        });
    }

    private void fuzzyQuery(final String input) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }

        disposable = new DisposableObserver<List<String>>() {
            @Override
            protected void onStart() {
                super.onStart();
                progressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onNext(final List<String> value) {
                String[] arr = new String[value.size()];
                value.toArray(arr);
                fuzzyList.setAdapter(new StringArrayAdapter(
                        CheckInOperationItemSelectionActivity.this,
                        android.R.layout.simple_list_item_1,
                        android.R.id.text1,
                        arr));
                fuzzyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent();
                        intent.putExtra("key", key);
                        intent.putExtra("value", value.get(position));
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
            }

            @Override
            public void onError(Throwable e) {
                progressBar.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onComplete() {
                progressBar.setVisibility(View.INVISIBLE);
            }
        };

        mapUtil.getCheckInOperationSelection(key, input, "", vehicleInformationDetail.getBrand_code(), disposable);
    }

    public void directReturn(View view) {
        Intent intent = new Intent();
        intent.putExtra("key", key);
        intent.putExtra("value", fuzzyEdit.getText().toString());

        if (TextUtils.isEmpty(fuzzyEdit.getText().toString())) {
            setResult(RESULT_CANCELED, intent);
            Toast.makeText(CheckInOperationItemSelectionActivity.this, "没有输入数据", Toast.LENGTH_SHORT).show();
        } else {
            setResult(RESULT_OK, intent);
        }
        finish();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (start >= 0) {
            handler.removeCallbacks(queryRunnable);
            handler.postDelayed(queryRunnable, 500);
        } else {
            if (disposable != null && !disposable.isDisposed())
                disposable.dispose();

            fuzzyList.setAdapter(null);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    Runnable queryRunnable = new Runnable() {
        @Override
        public void run() {
            fuzzyQuery(String.valueOf(fuzzyEdit.getText()));
        }
    };
}
